# -*- coding: utf-8 -*-

from odoo import models, fields, api
from odoo.exceptions import ValidationError


class DeviceCategory(models.Model):
    """设备类别模型"""
    _name = 'device.category'
    _description = '设备类别管理'
    _order = 'sequence, name'
    _parent_name = "parent_id"
    _parent_store = True
    _rec_name = 'complete_name'
    
    name = fields.Char('类别名称', required=True)
    complete_name = fields.Char('完整名称', compute='_compute_complete_name', recursive=True, store=True)
    code = fields.Char('类别编码', required=True)
    description = fields.Text('类别描述')
    
    # 父子关系
    parent_id = fields.Many2one('device.category', '上级类别', ondelete='cascade')
    parent_path = fields.Char(index=True)
    child_ids = fields.One2many('device.category', 'parent_id', '下级类别')
    
    # 基础信息
    sequence = fields.Integer('排序', default=10)
    status = fields.Boolean('状态', default=True)
    
    # 创建和修改信息
    create_time = fields.Datetime('创建时间', default=fields.Datetime.now)
    update_time = fields.Datetime('更新时间', default=fields.Datetime.now)
    create_by = fields.Char('创建者')
    update_by = fields.Char('更新者')
    remark = fields.Text('备注')
    
    # 统计字段
    device_count = fields.Integer('设备数量', compute='_compute_device_count')
    
    @api.depends('name', 'parent_id.complete_name')
    def _compute_complete_name(self):
        for category in self:
            if category.parent_id:
                category.complete_name = f"{category.parent_id.complete_name} / {category.name}"
            else:
                category.complete_name = category.name
    
    @api.depends()
    def _compute_device_count(self):
        for category in self:
            # 计算本类别及所有子类别的设备数量
            all_category_ids = category.get_children_categories().ids + [category.id]
            category.device_count = self.env['device.equipment'].search_count([
                ('category_id', 'in', all_category_ids)
            ])
    
    @api.constrains('code')
    def _check_code_unique(self):
        for record in self:
            if self.search_count([('code', '=', record.code), ('id', '!=', record.id)]) > 0:
                raise ValidationError(f'类别编码 {record.code} 已存在，请使用其他编码。')
    
    @api.constrains('parent_id')
    def _check_parent_id(self):
        if not self._check_recursion():
            raise ValidationError('不能创建循环的类别层级关系。')
    
    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            vals['create_time'] = fields.Datetime.now()
            if self.env.user:
                vals['create_by'] = self.env.user.name
        return super().create(vals_list)
    
    def write(self, vals):
        vals['update_time'] = fields.Datetime.now()
        if self.env.user:
            vals['update_by'] = self.env.user.name
        return super().write(vals)
    
    def get_children_categories(self):
        """获取所有子类别"""
        return self.search([('parent_path', '=like', self.parent_path + '%')])

